package cn.gcjxsc.service.merchant;

import cn.gcjxsc.entity.merchant.StoreSetting;
import cn.gcjxsc.repository.merchant.StoreSettingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author pumbaa
 * @since 1.0
 */
@Service
public class StoreSettingService {
    @Autowired
    private StoreSettingRepository settingRepository;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询店铺配置信息
     *
     * @param storeId 店铺id
     * @return
     */
    public Map<String, String> findSetting(Integer storeId) {
        List<StoreSetting> settings = settingRepository.findByStoreId(storeId);
        Map<String, String> data = new HashMap<>();
        for (StoreSetting setting : settings) {
            data.put(setting.getName(), setting.getValue());
        }
        return data;
    }

    /**
     * 查询店铺配置,带缓存功能
     *
     * @param storeId 店铺id
     * @return
     */
    public Map<String, String> findCacheSetting(Integer storeId) {
        HashOperations<String, String, String> ops = redisTemplate.opsForHash();
        Map<String, String> entries = ops.entries(buildKey(storeId));
        if (entries.isEmpty()) {
            entries = findSetting(storeId);
            ops.putAll(buildKey(storeId), entries);
        }
        return entries;
    }

    /**
     * 保存或更新店铺设置
     *
     * @param storeId 店铺id
     * @param params  参数
     */
    @Transactional
    public void saveOrUpdate(Integer storeId, Map<String, String> params) {
        List<StoreSetting> settings = settingRepository.findByStoreId(storeId);
        List<String> keys = new ArrayList<>();

        Set<String> excludeNames = new HashSet<>();
        for (StoreSetting setting : settings) {
            String name = setting.getName();
            keys.add(name);

            if (params.get(name) != null) {
                setting.setValue(params.get(name));
                excludeNames.add(name);
            }
        }

        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            if (excludeNames.contains(key)) {
                continue;
            }
            StoreSetting setting = new StoreSetting();
            setting.setStoreId(storeId);
            setting.setName(key);
            setting.setValue(entry.getValue());
            settings.add(setting);

            keys.add(key);
        }

        settingRepository.save(settings);
        redisTemplate.opsForHash().delete(buildKey(storeId), keys.toArray(new Object[keys.size()]));
    }

    private String buildKey(Integer storeId) {
        return "sconfig_" + storeId;
    }
}
